const Router = require("@koa/router");
const router = new Router();
const {
  Login,
  canSendCaptcha,
  Mobileregistation,
  Uploadpassword,
  Modifytheuser,
} = require("@/config/valiData");

const { modelUser } = require("@/models/collection");

const { VerCode, queryCode } = require("@/alicode/index");

const { gentoken } = require("@/token/jwt");

const { Auth } = require("@/token/auth");

const crypto = require("crypto");
const moment = require("moment");
moment.locale("zh-cn");

//小程序端:发送验证码
router.get("/vercode", async (ctx) => {
  const { phoneNumbers } = ctx.query;
  canSendCaptcha(phoneNumbers);
  const res = await VerCode(phoneNumbers);
  if (res.body.code == "OK" && res.body.message == "OK") {
    ctx.send("SUCCESS", 200, { bizId: res.body.bizId, message: "发送成功" });
  } else {
    ctx.send("ERROR", 400, res.body);
  }
});

//小程序端：手机号验证码登录
router.post("/mobile-registration", async (ctx) => {
  const { mobile, code, bizId } = ctx.request.body;
  //校验
  Mobileregistation(mobile, code, bizId);
  //校验验证码是否正确
  await queryCode(mobile, bizId, code);
  //判断用户之前是否已有账号
  const res = await modelUser
    .find({ mobile }, { mobile: false, my_tags: false })
    .lean(); //lean()返回纯json对象
  console.log(res);
  if (res.length > 0) {
    //已有账户
    // console.log(gentoken(res[0]._id));
    const token = { user_Token: gentoken(res[0]._id) };
    ctx.send("SUCCESS", 200, { ...res[0], ...token });
  } else {
    //没有账户
    const nickname = "用户_" + mobile.slice(-4);
    await modelUser.create({ mobile, nickname });
    const userData = await modelUser
      .find({ mobile }, { mobile: false, my_tags: false })
      .lean();
    const token = { user_Token: gentoken(userData[0]._id) };
    ctx.send("SUCCESS", 200, { ...userData[0], ...token });
  }
});

//设置密码,修改密码
router.post("/upload-password", async (ctx) => {
  const { mobile, code, bizId, password } = ctx.request.body;
  Uploadpassword(mobile, code, bizId, password);
  //校验验证码是否正确
  await queryCode(mobile, bizId, code);
  //判断用户是否存在
  const res = await modelUser.find({ mobile }).lean();
  if (res.length > 0) {
    //创建哈希对象
    const hash = crypto.createHash("sha256").update(password);
    //生成哈希值
    const passwordHash = hash.digest("hex");
    await modelUser.findOneAndUpdate({ mobile }, { password: passwordHash });
    ctx.send("SUCCESS", 200, { msg: "密码修改成功" });
  } else {
    ctx.send("ERROR", 400, { msg: "用户不存在" });
  }
});

//小程序端：手机号和密码登录
router.post("/login", async (ctx) => {
  const { mobile, password } = ctx.request.body;
  Login(mobile, password);
  //创建哈希对象
  const hash = crypto.createHash("sha256").update(password);
  //生成哈希值
  const passwordHash = hash.digest("hex");
  const res = await modelUser
    .find({ mobile, password: passwordHash }, { mobile: false, my_tags: false })
    .lean();

  if (res.length > 0) {
    const token = { user_Token: gentoken(res[0].uid) };
    ctx.send("SUCCESS", 200, { ...res[0], ...token });
  } else {
    ctx.send("账号或密码错误", 422, { msg: "用户名或密码错误" });
  }
});

//小程序端：编辑个人资料

router.post("/modify-the-user", new Auth().m, async (ctx) => {
  const { avatarUrl, nickname, gender, birthday, city, backdrop } =
    ctx.request.body;
  Modifytheuser(avatarUrl, nickname, gender, birthday, city, backdrop);
  //计算年龄
  const age = moment().diff(moment(birthday, "YYYY-MM-DD"), "years");
  const res = await modelUser.findOneAndUpdate(
    { uid: ctx.auth.uid },
    { avatarUrl, nickname, gender, birthday, city, backdrop, age },
    { new: true, select: { my_tags: false, uid: false, mobile: false } }
  );
  ctx.send("SUCCESS", 200, res);
});

// router.get('/test',new Auth().m,async ctx=>{
//    ctx.send('SUCCESS',200,{msg:'test'})
// })
module.exports = router.routes();
